<?php	
namespace Shopmanage\Model;
use Think\Model;
class CheckToolsModel{
   public $ToolStr;
   public $ToolName;
   public $UserNick;
   public $ToolType;
   public $IsvCode;
   public $Wurl;
   public $tool;
   public $toolid;
   public $tool_type;
   public $sid;
   public $c;
   public $where = '1=1';
   	private function _loadClient(){
		Vendor('taobaosdk.top.TopClient');
		Vendor('taobaosdk.top.RequestCheckUtil');
		$this->c =  new \TopClient();
		$this->c->appkey=C('SM_KEY');
		$this->c->secretKey=C('SM_SECRET');
	}
	public function myfilter($toolname){
		$cacheService = D("Shopmanage/Catche");
		$cacheService->delete("codes");
		$codes = $cacheService->get("codes");
		if(!$codes){
			$Tool = M("Tools");
			$codes = $Tool->getField("id,templet_code");
			$cacheService->set("codes",$codes,3600);
		}
		// print_r($codes);
		foreach($codes as $code){
			if($toolname==$code){
				return $toolname;
			}
		}
	}
	public function GetToolID($ctp,$tools){
		$ctp = $this->myfilter($ctp);
		if(!$tools){
			$Tool = M("Tools");
			$tools = $Tool->getField("templet_code,id,id");
		}
		if($ctp){
			$toolid = $tools[$ctp]["id"];
		}else{
			foreach($tools as $k=>$tool){
				if($tool["status"]==1){
					$toolid=$tool["id"];
					break;
				}
			}
		}
		return $toolid;
	}
	public function GetToolType($toolname){
		$Tool = M("Tools");
		return $Tool->where("`templet_code`='".$toolname."'")->getField("tool_type");
	}
	public function GetToolInfo($toolname){
		$Tool = M("Tools");
		return $Tool->where("`templet_code`='".$toolname."'")->getField("id,tool_type,pic_url,templet_code,name");
	}
	public function CheckToolStatus(){
		$Tool = M("Tools");
		$re = $Tool->join("LEFT JOIN sm_tools_status ON sm_tools.id= sm_tools_status.tool_id AND sm_tools_status.sid=".$this->sid)//->select();
			       ->where("sm_tools.templet_code='".$this->ToolName."'")
				   ->getField("sm_tools_status.status");
		$this->status=$re;
		return $re;
	}
   public function CheckISV(){
		$this->_loadClient();
		// if(APP_DEBUG){
			// $info["type"]='success';
			// $info["msg"]=$this->ToolName."工具已开通！";
			// $tool["name"]=$this->ToolName;
			// $tool["info"]=$info;
			// $tool["status"]=1;
			// $tool["deadline"]=date("Y-m-d H:i:s",time()+3600*24*100);
			// $tool["showend"]=GetTimeInfo(time()+3600*24*100);
			// $this->tool=$tool;
			// return;
		// }
		session("isvtool",null);
		$this->tool = session("isvtool");
		if(!$this->tool){
			Vendor("taobaosdk.top.request.VasSubscribeGetRequest");
			$req = new \VasSubscribeGetRequest();
			//查询店铺插件
			$req->setNick($this->UserNick);
			$req->setArticleCode($this->IsvCode);
			$resp = $this->c->execute($req);//print_r($resp);echo $resp->article_user_subscribes->article_user_subscribe[0]->deadline;
			$this->item_code=(string)$resp->article_user_subscribes->article_user_subscribe[0]->item_code;
			$this->deadline = (string)$resp->article_user_subscribes->article_user_subscribe[0]->deadline;
			if($resp->code){
				$info["type"]='error';
				$info["msg"]="抱歉，查询状态失败。";
				$status=0;
			}
			if($this->item_code){
				if((strtotime($this->deadline)-time())/(3600*24)<1){
					$info["type"]='warning';
					$info["msg"]=$this->ToolName."工具到期时间少于1天，请及时续订！";
					$status=0;
				}else{
					$info["type"]='success';
					$info["msg"]=$this->ToolName."工具已开通！";
					$status=1;
				}
			}else{
				$info["type"]='error';
				$info["msg"]="您尚未订购".$this->ToolName."或已到期，请及时订购！";
				$status=0;	
			}
			
			//开始计算每个月可用的天数，存入 $vaild。月份为key，可用天数为val。
			$alldays = $days = (strtotime($this->deadline)-time())/(3600*24);
			// 本月剩余天数： 
			$m = date("m");
			$deadmonth=false;// 指定最后一个到期月份。如果已经指定过了就不再指定。
			$firstmonth=false;// 指定第一个月份。如果已经指定过了就不再指定。
			// 本月之前月份置空
			for($j=1;$j<$m;$j++){
				$vaild[$j]["days"]=0;
			}
			// 下个月剩余天数：
			for($i=0;$i+$m<=12;$i++){
				$mdays = date("t",strtotime("2015-".($m+$i)."-01"));
				if($i==0){// 本月天数
					$mdays = date("t")-date("d");
				}
				if($days>=$mdays){
					$vaild[$m+$i]["days"]=$mdays;
					if($days>$mdays){
						$vaild[$m+$i]["curm"]="current-prev-re";
						if(!$firstmonth){
							$vaild[$m+$i-1]["curm"]="current-prev";
							$firstmonth=true;
						}
					}else{
						$vaild[$m+$i]["curm"].=" current";
						$deadmonth = true;
					}
					$days = $days-$mdays;
				}else{
					$vaild[$m+$i]["days"]=$days;
					if(!$deadmonth && $alldays>0){
						// 指定最后一个到期月份。如果已经指定过了就不再指定。
						if(!$firstmonth){
							$vaild[$m+$i-1]["curm"]="current-prev";
							$firstmonth=true;
						}
						$vaild[$m+$i]["curm"]="current";
						$deadmonth = true;
					}
					$days=0;
				}
			}
			ksort($vaild);
			$tool["vaild"]=$vaild;
			$tool["item_code"]=$this->item_code;
			$tool["name"]=$this->ToolName;
			$tool["info"]=$info;
			$tool["status"]=$status;
			$tool["deadline"]=$this->deadline;
			$tool["days"]=$alldays;
			$tool["showend"]=GetTimeInfo(strtotime($this->deadline));
			session("isvtool",$tool);
			$this->tool=$tool;
		}
   }

   public function GetAllTools(){
		$Tool = M("Tools");
		$this->where .= $this->tool_type?" AND `tool_type`=".$this->tool_type:"";
		$re = $Tool->where($this->where)->getField("sm_tools.templet_code,
				   sm_tools.id,
				   sm_tools.name,
				   sm_tools.tool_type,
				   sm_tools.pic_url,
				   sm_tools.gray_pic,
				   1 AS status");
		return $re;
   }
   public function ShowTools(){
		if($this->tool_type){
			$this->where.=" AND `sm_tools`.`tool_type`=".$this->tool_type;
		}
		$Tool = M("Tools");
		$re = $Tool->join("LEFT JOIN sm_tools_status ON sm_tools.id= sm_tools_status.tool_id AND sm_tools_status.sid=".$this->sid)//->select();
			       ->where($this->where)
				   ->getField("sm_tools.id,
				   sm_tools_status.status,
				   sm_tools.name,
				   sm_tools.tool_type,
				   sm_tools.templet_code,
				   sm_tools.pic_url,
				   sm_tools.gray_pic");
		foreach($re as $k=>$tool){
			if($tool["status"]==1){
				$t[$tool["templet_code"]]["pic_url"]=$tool["pic_url"];
			}else{
				$t[$tool["templet_code"]]["pic_url"]=$tool["gray_pic"];
			}
			$t[$tool["templet_code"]]["name"]=$tool["name"];
			$t[$tool["templet_code"]]["status"]=$tool["status"];
			$t[$tool["templet_code"]]["tool_type"]=$tool["tool_type"];
			$t[$tool["templet_code"]]["id"]=$k;
		}
		return $t;
   }
	public function GetUzTools(){
		$Tool = M("Tools");
		$re = $Tool->join("LEFT JOIN sm_tools_status ON sm_tools.id= sm_tools_status.tool_id AND sm_tools_status.sid=".$this->sid)//->select();
			       ->getField("
				   sm_tools.id,
				   sm_tools_status.status,
				   sm_tools.name,
				   sm_tools.shop_banner,
				   sm_tools.shop_banner_url,
				   sm_tools.shop_delivery_score,
				   sm_tools.shop_item_score,
				   sm_tools.shop_service_score,
				   sm_tools.shop_tmall,
				   sm_tools.shop_creattime,
				   sm_tools.shop_sellerCredit,
				   sm_tools.shop_auctionCount,
				   sm_tools.shop_sign_day,
				   sm_tools.shop_eidt_day,
				   sm_tools.shop_srt,
				   sm_tools.indu_art,
				   sm_tools.shop_srtp,
				   sm_tools.indu_arr,
				   sm_tools.shop_ccp,
				   sm_tools.indu_acr,
				   sm_tools.shop_punc,
				   sm_tools.indu_apts,
				   sm_tools.shop_gerd,
				   sm_tools.indu_iasgr,
				   sm_tools.isv_code,
				   sm_tools.live_buyers,
				   sm_tools.live_events,
				   sm_tools.upload_items,
				   sm_tools.upload_pics,
				   sm_tools.upload_shares,
				   sm_tools.new_commers,
				   sm_tools.send_gifts,
				   sm_tools.follow_weitao,
				   sm_tools.templet_code
				   ");
		foreach($re as $k=>$t){
			$re[$k]["shop_sign_day"]=date("Y-m-d",strtotime($re[$k]["shop_sign_day"]));
		}
		// echo $Tool->_sql();
		return $re;
   }
   public function AssignTool(){
		$Tool = M("ToolsStatus");
		$join="LEFT JOIN `sm_tools` ON `sm_tools_status`.`tool_id`=`sm_tools`.`id`";
		if($this->item_code==C("SM_CODE").'-1'){
			$version="普及版";
		}else{
			$version="游戏版";
		}
		$where=" AND `sm_tools`.`tool_type`=1";
		$tool_num_v1 = $Tool->where("`sm_tools_status`.`sid`=".$this->sid.$where)->join($join)->getField("count(`sm_tools_status`.`id`)");//echo $Tool->_sql();
		$where=" AND `sm_tools`.`tool_type`=3";
		$tool_num_v2 = $Tool->where("`sm_tools_status`.`sid`=".$this->sid.$where)->join($join)->getField("count(`sm_tools_status`.`id`)");//echo $Tool->_sql();
		// $where=" AND `sm_tools`.`tool_type`=2";
		// $tool_num_v3 = $Tool->where("`sm_tools_status`.`sid`=".$this->sid.$where)->join($join)->getField("count(`sm_tools_status`.`id`)");//echo $Tool->_sql();
		
		if(strtotime($this->deadline)-time()<=31*3600*24){
			$msg = '您订购的'.$version.'时间不足一个月，只能开通3款工具';
			$allow_tool_num=3;
		}else{
			$allow_tool_num=1000;
		}
		// elseif(strtotime($this->deadline)-time()<=92*3600*24){
			// $msg = '您订购的'.$version.'时间只有一个季度，只能开通3款工具';
			// $allow_tool_num=3;
		// }elseif(strtotime($this->deadline)-time()<=184*3600*24){
			// $msg = '您订购的'.$version.'时间只有半年，只能开通5款工具';
			// $allow_tool_num=5;
		// }elseif(strtotime($this->deadline)-time()<=365*3600*24){
			// $msg = '您订购的'.$version.'时间只有一年，只能开通7款工具';
			// $allow_tool_num=7;
		// }else{
			// $msg = '您订购了'.$version.'一年以上，不受限制';
			// $allow_tool_num=1000;
		// }
		$MT = M("Tools");
		$tool_type = $MT->where("`id`=".$this->toolid)->getField("tool_type");

		if($this->item_code==C("SM_CODE").'-1'){
			if(($tool_num_v1+$tool_num_v2)<$allow_tool_num){
				return $this->_addtool();
			}else{
				$this->err = $msg;
				return false;
			}
		}elseif($this->item_code==C("SM_CODE").'-2'){
			if(($tool_num_v1+$tool_num_v2)<$allow_tool_num){
				if($tool_type==1&&$tool_num_v1<$allow_tool_num){
					if(!$this->lowversion){
						$this->err = "您订购的是游戏版，开通普及版工具会占用游戏版工具数量，请问确实要开通吗？<button class=\"button lowversion\" type=\"button\">立即开通</button>";
						return false;
					}else{
						return $this->_addtool();
					}
				}elseif($tool_type==3&&$tool_num_v2<$allow_tool_num){
					return $this->_addtool();
				}
			}else{
				if($tool_type==3&&$tool_num_v2<$allow_tool_num&&!$this->lowversion){
					$this->err = "您订购的是游戏版，但是已有普及版工具开通，请问要关闭普及版工具，开通游戏版工具吗？本操作不可逆。<button class=\"button lowversion\" type=\"button\">立即开通</button>";
					return false;
				}
				if($tool_type==3&&$tool_num_v2<$allow_tool_num&&$this->lowversion){
					$re = $Tool->execute("DELETE `sm_tools_status` FROM `sm_tools_status` $join  WHERE `sm_tools_status`.`sid`=".$this->sid." AND `sm_tools`.`tool_type`=1");
					if($re){
						return $this->_addtool();
					}else{
						$this->err = "删除出错".$Tool->_sql();
						return false;
					}
				}
				$this->err = $msg;
				return false;
			}
		}
   }
   public function _addtool(){
		$data["sid"]=$this->sid;
		$data["tool_id"]=$this->toolid;
		$data["status"]=1;
		$data["cfg"]="";
		$Tool = M("ToolsStatus");
		$check = $Tool->where("`tool_id`='".$this->toolid."' AND `sid`=".$this->sid)->getField("id");
		if($check){
			$this->err = "工具已存在";
			return false;
		}else{
			$this->err = "成功开通";
			return $Tool->add($data);
		}
   }
}